package cn.ymjr.sys.util;

import cn.ymjr.sys.config.weixin.WeiXinConfig;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.jdom.JDOMException;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * Created by tiny on 2018/9/26.
 */
@SuppressWarnings("deprecation")
public class WxPayUtil {
    private static final Logger logger = Logger.getLogger(WxPayUtil.class);

    //订单支付
    public static Map<String, String> weixinPrePay(String sn, BigDecimal totalAmount, String description,String openid, HttpServletRequest request) {
        SortedMap<String, Object> parameterMap = new TreeMap<>();
        parameterMap.put("appid", WeiXinConfig.getAppId());
        parameterMap.put("body", StringUtils.abbreviate(description.replaceAll("[^0-9a-zA-Z\\u4e00-\\u9fa5 ]", ""), 600));
        parameterMap.put("mch_id", ConfigUtil.get("mch_id"));
        String randomString = PayCommonUtil.getRandomString(32);
        parameterMap.put("nonce_str",randomString);
        parameterMap.put("notify_url", "https://ymjr.jisugujia.cn/business/callback");//通知地址
        parameterMap.put("openid",openid);
        parameterMap.put("out_trade_no", sn);
        parameterMap.put("sign_type","MD5");
        parameterMap.put("spbill_create_ip", request.getRemoteAddr());
        BigDecimal total = totalAmount.multiply(new BigDecimal(100));
        java.text.DecimalFormat df=new java.text.DecimalFormat("0");
        parameterMap.put("total_fee", df.format(total));
        parameterMap.put("trade_type", "JSAPI");
        String sign = PayCommonUtil.createSign(parameterMap);
        parameterMap.put("sign", sign);
        String requestXML = PayCommonUtil.getRequestXml(parameterMap);
        logger.info(requestXML);
        String result = PayCommonUtil.httpsRequest("https://api.mch.weixin.qq.com/pay/unifiedorder", "POST",requestXML);
        logger.info(result);
        Map<String, String> map = null;
        try {
            map = PayCommonUtil.doXMLParse(result);
            logger.info("支付反回的数据："+map);
        } catch (JDOMException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return map;
    }
}
